package cn.itcast.searchapi;

import cn.itcast.documentapis.esClient;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.nested.ReverseNested;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCount;
import org.junit.jupiter.api.Test;

/**
 * @Description TODO : 以下代码显示了如何在搜索中添加两个聚合：
 * @Author: zj
 * @Date: 16:46 2019/3/8
 * @Version 1.0
 **/
public class aggregationsApi {

    @Test
    public void aggregationSc() {
        TransportClient client = esClient.getClient();

/*
        SearchResponse searchResponse = client.prepareSearch()
                .setQuery(QueryBuilders.matchAllQuery())
                .addAggregation(AggregationBuilders.terms("agg1").field("message"))
                .addAggregation(AggregationBuilders.dateHistogram("agg2")
                        .field("postDate").dateHistogramInterval(DateHistogramInterval.YEAR))
                .get();

        Terms agg1 = searchResponse.getAggregations().get("agg1");
        Histogram agg2 = searchResponse.getAggregations().get("agg2");
*/


        SearchRequestBuilder searchRequestBuilder = client.prepareSearch("bank")
                .addAggregation(
                        AggregationBuilders.terms("by_city").field("city.keyword")
                );

        System.out.println(searchRequestBuilder.toString());
        SearchResponse sr = searchRequestBuilder.get();
        Terms city = sr.getAggregations().get("by_city");

        for (Terms.Bucket bucket : city.getBuckets()) {
        }

    }
}
